import {ModalForm, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea} from '@ant-design/pro-components';
import React, {useEffect} from 'react';
import {Collapse} from "antd";
import {list} from '@/services/auto-keeper-cluster-api';
import {HAMode,IndexMode,MetaMode,StorageMode,BatchMode} from '@/services/ant-design-pro/enums';
import {enumInKey} from '@/utils/calculateUtil';

export type CreateOrUpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: API.Canal) => void;
  onSubmit: (values: API.Canal) => Promise<boolean>;
  updateModalOpen: boolean;
  values?: Partial<API.Canal>;
  title?: string;
};

const CreateOrUpdateForm: React.FC<CreateOrUpdateFormProps> = (props) => {

  const [useStoreMode, handleUseStoreMode] = React.useState<string>(props?.values?.canalParameter?.storageMode ? props?.values?.canalParameter?.storageMode : 'MEMORY');

  useEffect(() => {
    handleUseStoreMode(props?.values?.canalParameter?.storageMode ? props?.values?.canalParameter?.storageMode : 'MEMORY');
  }, [props?.values?.canalParameter?.storageMode]);

  return (<ModalForm
      title={props?.title}
      layout={"horizontal"}
      width="700px"
      labelCol={{span: 8}}
      onValuesChange={(values) => {
        if (values?.canalParameter?.storageMode)
          handleUseStoreMode(values?.canalParameter?.storageMode);
      }}
      open={props.updateModalOpen}
      onFinish={props.onSubmit}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          props.onCancel();
        }
      }}
    >
      <ProFormText initialValue={props?.values?.id} hidden={true} name='id'/>
      <ProFormText
        readonly={!!props?.values?.id}
        initialValue={props.values?.name}
        rules={[
          {
            required: true,
            message: 'Canal名称不能为空',
            max: 15,
            min: 4
          },
        ]}
        tooltip='注意:保存后不可修改'
        width="md"
        label="Canal名称"
        name="name"
      />
      <ProFormRadio.Group
        initialValue={props.values?.canalParameter?.runMode || 'EMBEDDED'}
        name={["canalParameter", "runMode"]}
        label="运行模式"
        radioType="radio"
        options={[
          {
            label: '嵌入式',
            value: 'EMBEDDED',
          },
          {
            label: '独立服务',
            value: 'SERVICE',
          },
        ]}/>
      <ProFormSelect
        width={"md"}
        initialValue={props.values?.canalParameter?.zkClusterId}
        rules={[
          {
            required: true,
            message: 'zookeeper集群不能为空',
          },
        ]}
        request={() => list({size: 1000}).then(res => res?.data?.map((a: API.AutoKeeperCluster) => ({
          label: a.clusterName,
          value: a.id
        })))}
        label="zookeeper集群"
        name={["canalParameter", "zkClusterId"]}
      />
      <ProFormRadio.Group
        initialValue={props.values?.canalParameter?.sourcingType || 'MYSQL'}
        name={["canalParameter", "sourcingType"]}
        label="数据源类型"
        radioType="radio"
        options={[
          {
            label: 'MYSQL',
            value: 'MYSQL',
          },
          {
            label: 'oceanbase',
            value: 'OCEANBASE',
          },
        ]}/>
      <ProFormTextArea
        initialValue={props.values?.canalParameter?.groupDbAddresses}
        width="md"
        tooltip='格式如 127.0.0.1:3306;(必须以分号结束，可添多个)'
        label="数据库地址"
        name={["canalParameter", "groupDbAddresses"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.dbUsername}
        fieldProps={{
          autoComplete: 'off',
        }}
        rules={[
          {
            required: true,
            message: '数据库帐号不能为空',
          },
        ]}
        width="md"
        label="数据库帐号"
        name={["canalParameter", "dbUsername"]}
      />
      <ProFormText.Password
        initialValue={props.values?.canalParameter?.dbPassword}
        rules={[
          {
            required: true,
            message: '数据库密码不能为空',
          },
        ]}
        fieldProps={{
          autoComplete: 'new-password',
        }}
        width="md"
        label="数据库密码"
        name={["canalParameter", "dbPassword"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.connectionCharset || 'UTF-8'}
        rules={[
          {
            required: true,
            message: 'charset不能为空'
          },
        ]}
        width="md"
        label="connectionCharset"
        name={["canalParameter", "connectionCharset"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.rsList}
        width="md"
        label="rsList"
        name={["canalParameter", "rsList"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.tenant}
        width="md"
        label="tenant"
        name={["canalParameter", "tenant"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.localBinlogDirectory}
        width="md"
        label="本地localBinlog目录"
        name={["canalParameter", "localBinlogDirectory"]}
      />
      <Collapse collapsible={'icon'} bordered={false} ghost items={[{
        key: '1', label: '位点自定义设置', forceRender:true, children:
          <>
            <ProFormRadio.Group
              initialValue={props.values?.canalParameter?.gtidEnable || false}
              name={["canalParameter", "gtidEnable"]}
              label="是否启用gtid位点"
              radioType="radio"
              options={[
                {
                  label: '是',
                  value: true,
                },
                {
                  label: '否',
                  value: false,
                },
              ]}/>
            <ProFormTextArea
              initialValue={props.values?.canalParameter?.positions?.join(';') || '{"journalName":"","position":0,"timestamp":0};'}
              width="md"
              transform={(value) =>(value && value!==''? {'canalParameter':{'positions':value.split(';')}} : null)}
              tooltip='示例：{"journalName":"","position":0,"timestamp":0}; (必须以分号结束，可添多个)'
              label="位点信息"
              name={["canalParameter", "positions"]}
            />
          </>
      }]}
      />
      <ProFormRadio.Group
        initialValue={props.values?.canalParameter?.tsdbEnable || false}
        name={["canalParameter", "tsdbEnable"]}
        label="是否开启表结构TSDB"
        tooltip='启用后可以获取表的元数据，用以支持虚拟列解析'
        radioType="radio"
        options={[
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ]}/>
      <ProFormText
        initialValue={props.values?.canalParameter?.rdsAccesskey}
        width="md"
        label="rds accesskey"
        name={["canalParameter", "rdsAccesskey"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.rdsSecretkey}
        width="md"
        label="rds secretkey"
        name={["canalParameter", "rdsSecretkey"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.rdsInstanceId}
        width="md"
        label="rds instanceId"
        name={["canalParameter", "rdsInstanceId"]}
      />
      <ProFormRadio.Group
        initialValue={props.values?.canalParameter?.storageMode || 'MEMORY'}
        name={["canalParameter", "storageMode"]}
        label="存储机制"
        radioType="radio"
        options={[
          {
            label: enumInKey(StorageMode,'MEMORY'),
            value: 'MEMORY'
          },
          {
            label: enumInKey(StorageMode,'FILE'),
            value: 'FILE'
          },
        ]}/>
      <ProFormRadio.Group
        hidden={useStoreMode !== 'MEMORY'}
        initialValue={props.values?.canalParameter?.storageBatchMode || 'MEMSIZE'}
        name={["canalParameter", "storageBatchMode"]}
        label="内存存储batch获取模式"
        radioType="radio"
        options={[
          {
            label: enumInKey(BatchMode,'MEMSIZE'),
            value: 'MEMSIZE',
          },
          {
            label: enumInKey(BatchMode,'ITEMSIZE'),
            value: 'ITEMSIZE',
          },
        ]}/>
      <ProFormText
        hidden={useStoreMode !== 'MEMORY'}
        initialValue={props.values?.canalParameter?.memoryStorageBufferSize || 32768}
        width="md"
        label="内存存储buffer记录数"
        rules={[
          {
            required: useStoreMode === 'MEMORY',
            message: '内存存储buffer记录数不能为空',
          },
        ]}
        name={["canalParameter", "memoryStorageBufferSize"]}
      />
      <ProFormText
        hidden={useStoreMode !== 'MEMORY'}
        initialValue={props.values?.canalParameter?.memoryStorageBufferMemUnit || 1024}
        width="md"
        rules={[
          {
            required: useStoreMode === 'MEMORY',
            message: '内存存储buffer记录单元大小不能为空'
          },
        ]}
        label="内存存储buffer记录单元大小"
        name={["canalParameter", "memoryStorageBufferMemUnit"]}
      />
      <ProFormText
        hidden={useStoreMode !== 'FILE'}
        initialValue={props.values?.canalParameter?.fileStorageDirectory}
        width="md"
        label="文件存储的目录位置"
        rules={[
          {
            required: useStoreMode === 'FILE',
            message: '文件存储的目录位置不能为空',
          },
        ]}
        name={["canalParameter", "fileStorageDirectory"]}
      />
      <ProFormText
        hidden={useStoreMode !== 'FILE'}
        initialValue={props.values?.canalParameter?.fileStorageStoreCount}
        width="md"
        label="文件存储store记录数"
        rules={[
          {
            required: useStoreMode === 'FILE',
            message: '文件存储store记录数不能为空',
          },
        ]}
        name={["canalParameter", "fileStorageStoreCount"]}
      />
      <ProFormText
        hidden={useStoreMode !== 'FILE'}
        initialValue={props.values?.canalParameter?.fileStorageRollverCount}
        width="md"
        label="文件存储store文件个数"
        rules={[
          {
            required: useStoreMode === 'FILE',
            message: '文件存储store文件个数不能为空',
          },
        ]}
        name={["canalParameter", "fileStorageRollverCount"]}
      />
      <ProFormText
        hidden={useStoreMode !== 'FILE'}
        initialValue={props.values?.canalParameter?.fileStoragePercentThresold}
        width="md"
        label="文件存储store存储占disk百分比"
        rules={[
          {
            required: useStoreMode === 'FILE',
            message: '文件存储store存储占disk百分比不能为空',
          },
        ]}
        name={["canalParameter", "fileStoragePercentThresold"]}
      />
      <ProFormRadio.Group
        initialValue={props.values?.canalParameter?.haMode || 'HEARTBEAT'}
        name={["canalParameter", "haMode"]}
        label="HA机制"
        radioType="radio"
        options={[
          {
            label:  enumInKey(HAMode,'HEARTBEAT'),
            value: 'HEARTBEAT',
          },
          {
            label: enumInKey(HAMode,'MEDIA'),
            value: 'MEDIA',
          },
        ]}/>
      <ProFormText
        initialValue={props.values?.canalParameter?.mediaGroup}
        width="md"
        label="media group key"
        name={["canalParameter", "mediaGroup"]}
      />
      <ProFormRadio.Group
        initialValue={props.values?.canalParameter?.detectingEnable || false}
        name={["canalParameter", "detectingEnable"]}
        label="是否开启心跳"
        radioType="radio"
        options={[
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ]}/>
      <ProFormTextArea
        initialValue={props.values?.canalParameter?.detectingSQL || 'insert into retl.xdual values(1,now()) on duplicate key update x=now()'}
        width="md"
        rules={[
          {
            required: true,
            message: '心跳sql不能为空',
          },
        ]}
        label="心跳sql"
        name={["canalParameter", "detectingSQL"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.detectingIntervalInSeconds || 5}
        width="md"
        label="心跳检测频率(秒)"
        name={["canalParameter", "detectingIntervalInSeconds"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.detectingTimeoutThresholdInSeconds || 30}
        width="md"
        label="心跳超时时间(秒)"
        name={["canalParameter", "detectingTimeoutThresholdInSeconds"]}
      />
      <ProFormText
        initialValue={props.values?.canalParameter?.detectingRetryTimes || 3}
        width="md"
        label="心跳超时时间(秒)"
        name={["canalParameter", "detectingRetryTimes"]}
      />
      <ProFormRadio.Group
        initialValue={props.values?.canalParameter?.heartbeatHaEnable || false}
        name={["canalParameter", "heartbeatHaEnable"]}
        label="是否开启心跳HA"
        radioType="radio"
        options={[
          {
            label: '是',
            value: true,
          },
          {
            label: '否',
            value: false,
          },
        ]}/>
      <Collapse collapsible={'icon'} bordered={false} ghost items={[{
        key: '2', label: '高级设置', forceRender:true, children:
          <>
            <ProFormRadio.Group
              initialValue={props.values?.canalParameter?.metaMode || 'MIXED'}
              name={["canalParameter", "metaMode"]}
              label="meta机制"
              radioType="radio"
              options={[
                {
                  label: enumInKey(MetaMode,'MEMORY'),
                  value: 'MEMORY',
                },
                {
                  label: enumInKey(MetaMode,'ZOOKEEPER'),
                  value: 'ZOOKEEPER',
                },
                {
                  label: enumInKey(MetaMode,'MIXED'),
                  value: 'MIXED',
                },
              ]}/>
            <ProFormRadio.Group
              initialValue={props.values?.canalParameter?.indexMode || 'MEMORY_META_FAILBACK'}
              name={["canalParameter", "indexMode"]}
              label="索引机制"
              radioType="radio"
              options={[
                {
                  label: enumInKey(IndexMode,'MEMORY'),
                  value: 'MEMORY',
                },
                {
                  label: enumInKey(IndexMode,'ZOOKEEPER'),
                  value: 'ZOOKEEPER',
                },
                {
                  label: enumInKey(IndexMode,'MIXED'),
                  value: 'MIXED',
                },
                {
                  label: enumInKey(IndexMode,'META'),
                  value: 'META',
                },
                {
                  label: enumInKey(IndexMode,'MEMORY_META_FAILBACK'),
                  value: 'MEMORY_META_FAILBACK',
                },
              ]}/>
            <ProFormText
              initialValue={props.values?.canalParameter?.port || 11111}
              width="md"
              label="服务端口"
              name={["canalParameter", "port"]}
            />
            <ProFormText
              initialValue={props.values?.canalParameter?.defaultConnectionTimeoutInSeconds || 30}
              width="md"
              label="默认连接超时(秒)"
              name={["canalParameter", "defaultConnectionTimeoutInSeconds"]}
            />
            <ProFormText
              initialValue={props.values?.canalParameter?.sendBufferSize || 16384}
              width="md"
              label="sendBufferSize"
              name={["canalParameter", "sendBufferSize"]}
            />
            <ProFormText
              initialValue={props.values?.canalParameter?.receiveBufferSize || 16384}
              width="md"
              label="receiveBufferSize"
              name={["canalParameter", "receiveBufferSize"]}
            />
            <ProFormText
              initialValue={props.values?.canalParameter?.fallbackIntervalInSeconds || 60}
              width="md"
              label="切换回退时间(秒)"
              name={["canalParameter", "fallbackIntervalInSeconds"]}
            />

          </>
      }]}/>
      <ProFormTextArea
        initialValue={props.values?.canalParameter?.blackFilter}
        width="md"
        label="过滤表达式"
        name={["canalParameter", "blackFilter"]}
      />
      <ProFormTextArea
        initialValue={props.values?.desc}
        width="md"
        label="描述信息"
        name="desc"
      />

    </ModalForm>
  );
};

export default CreateOrUpdateForm;
